import Dep from './Dep.js'
import Compile from './compile.js'

export default class Vue {

  constructor({ data, methods, created, el }) {
    this.$data = data
    this.$methods = methods
    this.created = created.bind(this)
    this.observe(this.$data)
    new Compile(this, el)
  }

  observe(data = {}) {
    if (data && typeof data === 'object') {
      Object.keys(data).forEach(key => {
        this.defineReactive(data, key, data[key])
        this.proxyDate(key)
      })
    }
  }

  proxyDate(key) {
    Object.defineProperty(this, key, {
      get() {
        return this.$data[key]
      },
      set(newValue) {
        this.$data[key] = newValue
      }
    })
  }

  // 数据劫持
  defineReactive(obj = {}, key = "", val = []) {
    this.observe(val)

    const dep = new Dep()
    Object.defineProperty(obj, key, {
      get() {
        Dep.target && dep.addDep(Dep.target)
        return val
      },
      set(newValue) {
        if (val !== newValue) {
          val = newValue
          dep.notify()
        }
      }
    })
  }
}